<?php

namespace App\Http\Controllers\Site;

use App\B2BProject\Site\HelperControllerBuildTrait;
use App\B2BProject\Custom\Business\Goods;
use App\B2BProject\Custom\Business\Store;
use App\B2BProject\Custom\Purchaser\CounterEnquiry;
use App\B2BProject\Custom\Purchaser\Enquiry;
use Auth;
use App\B2BProject\Area;
use App\B2BProject\Custom\Business\GoodsCategory;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Validator;

/**
 * 采购询盘
 * Class PurchaserController
 * @package App\Http\Controllers\Site
 */
class PurchaserController extends Controller
{
    use HelperControllerBuildTrait;

    public function __construct()
    {
        parent::__construct();

        $this->middleware('auth', ['except' => ['getList', 'getChoose', 'getGroomSupply', 'getHotShop']]);

        // TODO 中间件
        /* $this->middleware('purchaser.check', ['only' => ['postSave']]);*/
    }

    /**
     * 询盘分类列表
     * @return $this
     *
     */
    public function getList(Request $request)
    {
        $cid = '';
        $pid = 0;
        $request->query->set('page', $request->query('page', $request->page));
        $request->query->set('pageSize', $request->query('pageSize', $request->pageSize));

        $query = Enquiry::orderBy('created_at', 'desc')->Available();
        if ($goodType = $request->query('goodType')) {
            $category = GoodsCategory::with('children')->whereId($goodType)->firstOrFail();
            if ($category->parent_id == 0) {
                $in = [];
                foreach ($category->children as $child) {
                    $in[] = $child->id;
                }

                $query = $query->whereIn('secondary_category_id', $in);
            } else {
                $query = $query->where('secondary_category_id', $goodType);
            }
        }

        $info = $query->paginate($request->query('pageSize', 7));
        if (\Request::ajax()) {
            $listData = [];
            foreach ($info as $list) {
                $item       = [
                    'enquiry_id'        => $list->id,
                    'unit_price'        => $list->price,
                    'name'              => $list->title,
                    'minnum'            => $list->minimum_order,
                    'number'            => $list->amount,
                    'supplier_address1' => Area::where('id', $list->province_id)->first()->name,
                    'supplier_address2' => Area::where('id', $list->city_id)->first()->name,
                    'release_date'      => date('Y-m-d', strtotime($list->created_at)),
                ];
                $listData[] = $item;
            }

            return response()->json([
                'data'           => $listData,
                'pagingConfData' => [
                    'page'     => $info->currentPage(),
                    'pageSize' => $request->query('pageSize'),
                    'total'    => $info->total(),
                ],
            ]);

        }

        return view('host/purchaser')->with('cid', $cid)->with('pid', $pid);
    }

    /**
     * 热销产品 随机读取商品中的数据
     * @return \Illuminate\Http\JsonResponse
     */
    public function getHotShop()
    {
        $info = Goods::HasCover()->take(5)->get();

        $data = [];
        foreach ($info as $value) {
            $data['data'][] = [
                'imgsrc' => $value->cover(),
                'price'  => $value->original_price,
                'id'     => $value->id,
                'title'  => $value->name,
                'href'   => route('goods.detail', [$value->id]),

            ];
        }

        return response()->json($data);
    }

    /**
     * 推荐供应商
     * @return \Illuminate\Http\JsonResponse
     */
    public function getGroomSupply()
    {
        $stores = Store::has('goods', '>', 5)->where('store_logo', '!=', '')->take(3)->get();
        $data   = [];
        foreach ($stores as $store) {
            $information    = $store->member->information;
            $data['data'][] = [
                'imgsrc' => $store->store_logo,
                'title'  => '很懒，什么都没有留下',
                'id'     => $store->id,
                'name'   => $information->company,
                'href'   => route('store', [$store->id]),
            ];
        }

        return response()->json($data);
    }

    /**
     * 保存询盘信息到数据库
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\RedirectResponse
     *
     */
    public function postSave(Request $request)
    {
        try {
            if (Auth::user()->class == 1) {

                $validator = Validator::make(
                    $request->except(['_token']),
                    [
                        'enquiry_id'    => 'exists:enquiries,id',  //验证一定存在该供应商的信息
                        'contact_name'  => 'required',
                        'amount'        => "required|numeric",
                        'price'        => "required|numeric",
                        'contact_phone' => 'required',
                        'province'      => 'required|exists:areas,id,level,1',
                        'city'          => 'required|exists:areas,id,level,2',
                        'county'        => 'required|exists:areas,id,level,3',
                    ]
                );
                if ($validator->fails()) {
                    return redirect()->back();
                }

                \DB::transaction(function () use ($request) {
                    $data = $request->only([
                        'amount',
                        'contact_name',
                        'contact_phone',
                        'price',
                    ]);// 只取这些数据

                    $data['province_id'] = $request->input('province');
                    $data['city_id']     = $request->input('city');
                    $data['county_id']   = $request->input('county');

                    $counterEnquiry = CounterEnquiry::create($data);
                    $counter        = Enquiry::findOrFail($request->input('enquiry_id'));
                    $counter->counter()->save($counterEnquiry);
                    Auth::user()->counters()->save($counterEnquiry);
                    //TODO 这里数据库的值减少 是在这里减还是应该审核过后再减？
                    Enquiry::where('id',
                        $request->input('enquiry_id'))->decrement('amount', $request->input('amount'));
                });

                return redirect()->back();
            } else {
                //TODO 用户类型不匹配 提示信息
                return redirect()->back();
            }
        } catch (UserTypeException $e) {
            return redirect('error', 403);
            throw $e;
        }

    }
}
